#include "sharedmemory.hpp"

int main()
{
    My_Shared_Memory::SharedMemory myshm(FIFO_NAME, 400, IPC_CREAT | IPC_EXCL | 0666);
    int *myarr = (int *)myshm.Get();
    std::cout << &myarr << std::endl;
    while (1)
    {
        sleep(1);
        myarr[0] += 1;

        if (myarr[0] > 30)
        {
            break;
        }
    }
    return 0;
}

int server()
{
    int myshmarr[100];
    // 获得KEY
    key_t mykey = ftok(FIFO_PATHNAME, 'A');
    if (mykey <= 0)
    {
        std::cout << mykey << std::endl;
        ERROR_MESSAGE("ftok");
    }

    // 创建共享内存
    umask(0);
    int myshmid = shmget(mykey, sizeof(myshmarr), IPC_CREAT | IPC_EXCL | 0666);
    if (myshmid == -1)
    {
        ERROR_MESSAGE("shmget");
    }

    // 附加共享内存
    int *newshared = (int *)shmat(myshmid, nullptr, 0);
    if (newshared == (int *)-1)
    {
        ERROR_MESSAGE("shmat");
    }
    std::cout << &newshared << std::endl;
    std::cout << &myshmarr << std::endl;
    while (1)
    {
        sleep(1);
        newshared[0] += 1;

        if (newshared[0] > 30)
        {
            break;
        }
    }
    // 共享内存分离
    shmdt(newshared);
    sleep(5);
    // 共享内存删除
    int ctlret = shmctl(myshmid, IPC_RMID, nullptr);
    if (ctlret == -1)
    {
        ERROR_MESSAGE("shmctl");
    }

    return 0;
}
